package com.heyun.controller;

import com.heyun.constant.Constants;
import com.heyun.entity.dto.BehaviorsLogDTO;
import com.heyun.entity.dto.LoginDTO;
import com.heyun.entity.pojo.StudentPOJO;
import com.heyun.entity.vo.LoginResult;
import com.heyun.result.Result;
import com.heyun.service.PermissionService;
import com.heyun.service.UserService;
import com.heyun.utils.JwtUtil;
import com.heyun.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 身份校验
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userService;

    @Value("heyun")
    private String SecretKey;
    @Value("8640000000")
    private long ttl;

    /**
     * 统一登录接口
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result Login(@RequestBody LoginDTO loginDTO, HttpSession session) {

        ArrayList<StudentPOJO> stuPOJO = permissionService.login(loginDTO);
        if (stuPOJO.size() > 0){
            Map<String,Object> claims = new HashMap();
            claims.put("id",stuPOJO.get(0).getUserId());
            claims.put("username",stuPOJO.get(0).getUsername());
            claims.put("role",stuPOJO.get(0).getRoleId().toString());
            // 存储用户名到session
            session.setAttribute("user",stuPOJO.get(0).getUsername());
            System.out.println("session:"+session.getAttribute("user"));
            String token = JwtUtil.genToken(SecretKey, ttl, claims);
            LoginResult lr = new LoginResult(token,stuPOJO.get(0).getRoleId());
            return Result.success(lr);
        }
        return Result.error(Constants.LOGIN_FAIL);
    }
    @PutMapping("/log")
    public Result AddLog(@RequestParam String behavior,@RequestParam String place){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        BehaviorsLogDTO bl = new BehaviorsLogDTO(userId,behavior, place);
        return Result.success(userService.BehaviorsLog(bl));
    }

//    @PostMapping("/login/teacher")
//    public Result teacherLogin(LoginDTO loginDTO){
//        return Result.success(permissionService.login(loginDTO));
//    }
//    @PostMapping("/login/admin")
//    public Result adminLogin(LoginDTO loginDTO){
//        return Result.success(permissionService.login(loginDTO));
//    }
}
